<script>
/* 企业季度报表 */
import QuarterlyAccountSearchForm from '@/mixins/quarterly-account-search-form'
import QuarterlyAccountDetails from '@/mixins/quarterly-account-details'
import QuarterlyAccountTableLists from '@/mixins/quarterly-account-table-lists'
import {
  COMPANY_PRODUCT_LIST,
  CONDITION_TABLE_OF_MAJOR_ENERGY_CONSUMING_EQUIPMENT,
  DETAILED_LIST_OF_COMPANY_INDICATORS,
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_TABLE,
  ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE,
  PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE, TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT,
} from '@/config'

import { simpleAoa2Sheet } from '@/utils/sheet'
import {
  importCompanyIndicatorDetails,
  importCompanyProduct,
  importEnergyConsumptionStructure,
  importEnergyConsumptionStructureSchedule,
  importEquipmentStatus,
  importGoalCompletionStatus,
  importProductEnergyConsumption,
  importReconstructionProject,
} from '@/api/enterpriseQuarterlyReport'

export default {
  name: 'quarterly-account',
  mixins: [
    QuarterlyAccountSearchForm,
    QuarterlyAccountTableLists,
    QuarterlyAccountDetails
  ],
  computed: {
    // 导入数据方法
    _import () {
      const tableAccountId = Number(this.tableAccountId)
      let method = null
      switch (tableAccountId) {
        case PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID:
          method = importGoalCompletionStatus
          break
        case TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID:
          method = importProductEnergyConsumption
          break
        case CONDITION_TABLE_OF_MAJOR_ENERGY_CONSUMING_EQUIPMENT.ID:
          method = importEquipmentStatus
          break
        case ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID:
          method = importReconstructionProject
          break
        case ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID:
          method = importEnergyConsumptionStructure
          break
        case COMPANY_PRODUCT_LIST.ID:
          method = importCompanyProduct
          break
        case DETAILED_LIST_OF_COMPANY_INDICATORS.ID:
          method = importCompanyIndicatorDetails
          break
        case ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID:
          method = importEnergyConsumptionStructureSchedule
          break
      }
      return method
    },
    titleWidth () {
      let w = 200;
      if (this.showButton) {
        w += 300
      }
      if (this.useAutoSave) {
        w += 100
      }
      return w
    }
  },

  methods: {
    importData (file) {
      const params = new FormData()
      params.append(TABLE_FIELD_YEAR, String(this.year))
      params.append(TABLE_FIELD_QUARTER, String(this.quarter))
      params.append('file', file)
      params.append('tenantId', this.enterpriseId ? String(this.enterpriseId) : '')

      if (this._import) {
        return this._import(params).then(res => {
          if (res.code === 200) {
            this.$message.success('导入成功')
          }
        }).finally(() => {
          this.$refs.fileInput && (this.$refs.fileInput.value = '')
        })
      }
    },
    exportData () {
      const quarterlyAccountTable = this.$refs.quarterlyAccountTable
      const flattenColumns = quarterlyAccountTable.flattenColumns
      const lists = quarterlyAccountTable.getData() || [];
      const summary = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.summary
      const informer = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.getInformer && this.$refs.quarterlyAccountTable.getInformer()

      const fill = (v) => flattenColumns.map(col => {
        const prop = col.prop
        return v[prop] || ''
      })

      const aoa = [
        (flattenColumns || []).map(v => v.label),
      ]

      lists.forEach(v => {
        const data = fill(v)
        // console.log(data);
        aoa.push(data)
      })

      // 合计
      if (summary) {
        const d = summary.data.reduce((acc, v) => {
          acc[v.key] = String(v.value || '')
          return acc
        }, {})
        const data = fill(d)
        aoa.push(data)
      }

      // 本年综合能源消费量（当量值）
      // 上年综合能源消费量（当量值）
      // consumptionLastYear consumptionThisYear
      const consumptionThisYear = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.currentValue
      const consumptionLastYear = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.previousValue
      if (consumptionLastYear != null && consumptionThisYear != null) {
        aoa.push([])
        aoa.push(
          ['本年综合能源消费量（当量值）', consumptionThisYear || '', '上年综合能源消费量（当量值）', consumptionLastYear || '']
        )
      }

      const appendInformant = v => ([
        fill({}),
        fill([]),
        ['填报负责人：', v.personInCharge, '填报人：', v.informer, '电话：', v.telephone, '填报日期：', v.fillInDate],
      ])
      aoa.push(
        ...appendInformant(informer)
      )

      const fileName = `${this.year}年第${this.quarter}季度${this.tableName}.xlsx`
      simpleAoa2Sheet(aoa, fileName)
    },
    fileChangeHandler (evt) {
      evt.stopPropagation()
      const target = evt.target
      const file = target.files[0]
      if (file) {
        this.$confirm('导入将覆盖原来的数据，确定要导入吗？').then(() => {
          const result = this.importData(file)
          if (result && result.then) {
            result.then(() => {
              this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.refresh && this.$refs.quarterlyAccountTable.refresh()
            })
          }
        }).catch(() => {
          target.value = ''
        })
      }
    },
  },
}
</script>

<template>
  <div class="padding flex direction-column width-100 height-100">
    <div class="search-form">
      <el-form inline>
        <el-form-item label="年份">
          <el-date-picker type="year" :clearable="false" v-model="year" value="yyyy" value-format="yyyy"></el-date-picker>
        </el-form-item>
        <el-form-item label="季度">
          <el-select v-model="quarter">
            <el-option v-for="option in options" :key="option.value" v-bind="option"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="flex-1 overflow-auto dark-table-wrapper">
      <el-table
        v-loading="loading"  :data="lists"
        height="100%"
        :row-style="rowStyle"
        :header-cell-style="{
          color: 'white',
          backgroundColor: themeColor,
        }"
      >
        <div slot="empty" class="empty-lists">
          <i class="i-custom:search"></i>
          <span class="empty-text">暂无数据</span>
        </div>
        <el-table-column v-for="column in columns" :key="column.prop" v-bind="column"></el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="{ row }">
            <td-button title="编辑" @click="edit(row)">
              <i class="i-custom:editor"></i>
            </td-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="showTableAccount" class="padding table-account-details">
      <component
        :is="tableComponent"
        ref="quarterlyAccountTable"
        :year="year" :quarter="quarter"
        :columns="tableColumns" :name="tableName" :t-id="tableAccountId"
        :enterprise-id="enterpriseId" :enterprise-name="enterpriseName"
        :readonly="readonly"
      >
        <template #title="{ title, seriesNo }">
          <div class="flex align-center position-relative">
            <el-button type="primary" icon="el-icon-back" circle @click="back(!showButton)"></el-button>
            <span v-if="autoSaveAble" class="last-save-timestamp">最近保存 {{ lastSaveTimestamp }}</span>
            <h2 :title="title" class="margin-horizontal-auto text-truncate"
              :style="'max-width: calc(100% - '+titleWidth+'px);font-weight: normal;'">
              {{title}}
              <small v-if="seriesNo">（{{seriesNo}}）</small>
            </h2>
            <template v-if="showButton">
              <el-button type="success" @click="loadPrevData">加载上期数据</el-button>
              <el-button type="primary" @click="saveStage">暂存</el-button>
              <el-button type="danger" @click="report">上报</el-button>
              <el-button type="primary" style="position: relative;">
                导入
                <input ref="fileInput" type="file" accept=".xlsx, .xls" @change="fileChangeHandler" class="file-input">
              </el-button>
            </template>
            <el-button type="primary" @click="exportData">导出</el-button>
          </div>
        </template>
      </component>
    </div>
  </div>
</template>
